import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Button, notification, Radio, Modal, Upload, Tag, Tooltip } from 'antd';
import { addKeyWord, hasKeyWord } from '@/services/resource';
import styles from '@/pages/algorithmModel/dataCenter/style.less';

const { TextArea } = Input;
const FormItem = Form.Item;
const containSpecial = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
    },
};


class Edit extends React.Component {
    constructor(argus) {
        super(argus);

        this.state = {
            loading: false,
            sameWord: [],
            inputVisible: false,
            inputValue: '', // 同义词新增时 输入的内容
        };
    }

    componentDidMount() {
        const { id, sameWordStr } = this.props;
        Boolean(id) && sameWordStr && this.setState({ sameWord: sameWordStr.split(','), })
    }

    infoToParent(key) {
        this.props.callBack(key, { keywordId: '' });
    }

    // 名称校验
    onNameBlur = e => {
        const keywordNameStrict = e.target.value;
        keywordNameStrict && hasKeyWord({ data: { keywordNameStrict } }).then(res => {
            if (res.retCode === '0') {
                if (res.data.total > 0) {
                    this.props.form.setFields({
                        keyword_name: {
                            value: keywordNameStrict,
                            errors: [new Error('名称已存在!')],
                        },
                    });
                    return;
                }
            }
        })
    }

    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        const { sameWord, } = this.state;
        const { form, id, labelId } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                const isContainSpecial = containSpecial.test(sameWord.join(''));
                if (isContainSpecial) {
                    notification['warning']({
                        message: '警告',
                        key: '标签内容不允许特殊字符',
                        description: '标签内容不允许特殊字符',
                    });
                    return;
                }
                _this.setState({ loading: true, })
                addKeyWord(Boolean(id) ? { keywordId: id, keywordSame: sameWord.join(',') || null } : { keywordName: values.keyword_name, dictionaryLabelId: labelId , keywordSame: sameWord.join(',') || null }, Boolean(id) ? 'edit' : 'add').then(res => {
                    if (res.retCode == '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '添加关键词',
                            description: '添加关键词成功',
                        });
                        _this.infoToParent(false);
                    } else {
                        _this.setState({ loading: false, })
                    }
                })
            }
        });
    };

    /*
    * 新增标签   开始
    */
    handleClose = removedTag => {
        const sameWord = this.state.sameWord.filter(tag => tag !== removedTag);
        this.setState({ sameWord });
    };

    showInput = () => {
        this.setState({ inputVisible: true }, () => this.input.focus());
    };

    handleInputChange = e => {
        this.setState({ inputValue: e.target.value });
    };

    handleInputConfirm = () => {
        const { inputValue } = this.state;
        // const isContainSpecial = containSpecial.test(inputValue.trim());
        // if (isContainSpecial) {
        //     this.props.form.setFields({
        //         sameWord: {
        //             errors: [new Error('标签内容不允许特殊字符')],
        //         },
        //     });
        //     this.setState({inputValue:''})
        //     return;
        // }
        let { sameWord } = this.state;
        if (inputValue.trim() && sameWord.indexOf(inputValue) === -1) {
            sameWord = [...sameWord, inputValue.trim()];
        }
        this.setState({
            sameWord,
            inputVisible: false,
            inputValue: '',
        });
    };

    saveInputRef = input => (this.input = input);
    /*
    * 新增标签   结束
    */

    render() {
        const { getFieldDecorator } = this.props.form;
        const { loading, sameWord, inputVisible, inputValue, } = this.state;
        const { isShowAddKeyWordModel, id } = this.props;


        return (
            <span>

                <Modal
                    title={`${Boolean(id) ? '编辑' : '添加关键词'}`}
                    maskClosable={false}
                    visible={isShowAddKeyWordModel}
                    width={600}
                    onCancel={this.infoToParent.bind(this, false)}
                    footer={[
                        <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
                        <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
                    ]}
                >
                    <Form>
                        {!Boolean(id) &&
                            <Form.Item label="关键词名称" {...formItemLayout}>
                                {getFieldDecorator('keyword_name', {
                                    rules: [{ required: true, pattern: /^[\u4e00-\u9fa5\w]{1,16}$/, message: '关键词不为空、不允许特殊字符且长度不超过16!' }],
                                })(
                                    <Input placeholder="关键词名称" onBlur={this.onNameBlur.bind(this)} />
                                )}
                            </Form.Item>
                        }
                        <Form.Item label='同义词'  {...formItemLayout} >
                            {getFieldDecorator('sameWord', {
                                rules: [
                                    {
                                        message: `请添加同义词!`,
                                        validator: sameWord && sameWord.length,
                                    },
                                ],
                            })(
                                <div>
                                    {sameWord &&
                                        sameWord.map((tag, index) => {
                                            const isLongTag = tag.length > 20;
                                            const tagElem = (
                                                <Tag
                                                    key={tag + index}
                                                    closable={!tag.labelId}
                                                    onClose={() => this.handleClose(tag)}
                                                >
                                                    {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                                                </Tag>
                                            );
                                            return isLongTag ? (
                                                <Tooltip title={tag}>
                                                    {tagElem}
                                                </Tooltip>
                                            ) : (
                                                    tagElem
                                                );
                                        })}
                                    {inputVisible && (
                                        <Input
                                            ref={this.saveInputRef}
                                            type="text"
                                            size="small"
                                            style={{ width: 80 }}
                                            value={inputValue}
                                            onChange={this.handleInputChange}
                                            onBlur={this.handleInputConfirm}
                                            onPressEnter={this.handleInputConfirm}
                                            maxLength={16}
                                        />
                                    )}
                                    {!inputVisible && (
                                        <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }} >
                                            <PlusOutlined /> 添加
                                        </Tag>
                                    )}
                                </div>
                            )}
                        </Form.Item>
                    </Form>
                </Modal>
            </span>
        );
    }
}

const AddLabel = Form.create()(Edit);

export default AddLabel;